<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnEmpty from '@tuniao/tnui-vue3-uniapp/components/empty/src/empty.vue'
import TnSearchBox from '@tuniao/tnui-vue3-uniapp/components/search-box/src/search-box.vue'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index.vue'
import circles from '@/api/circles.js'
import { FILE_URL } from '@/api/config.js'

// 导航栏的高度
const navbarHeight = ref(0)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
const state = reactive({
  searchName: '',
  circlesTypeName: '',
  // 侧边栏分类数据
  tabbar: [],
  subClassify: [],
  // 分类里面的内容信息
  classifyContent: {
    // 子栏目
    subClassifyTabbar: [],
    // 显示子栏目分类选项
    showSubClassifyTabbar: false,
  },
  // 分类菜单item的信息
  tabbarItemInfo: [],
  // scrollView的top值
  scrollViewBasicTop: 0,
  // scrollView的高度
  scrollViewHeight: 0,
  // 左边scrollView的滚动高度
  leftScrollViewTop: 0,
  // 右边scrollView的滚动高度
  rightScrollViewTop: 0,
  // 当前选中的tabbar序号
  currentTabbarIndex: 0,
})

const changeSearchBox = () => {
  state.currentTabbarIndex = 0
  getCirclesLists()
}

const getCirclesLists = () => {
  circles
    .circlesLists({
      circles_name: state.searchName,
    })
    .then((res) => {
      if (res.code == 1) {
        state.tabbar = res.data.map((item: { name: any }) => item.name)
        state.subClassify = res.data

        if (state.circlesTypeName != '') {
          state.tabbar.forEach((item, index) => {
            if (item === state.circlesTypeName) {
              state.currentTabbarIndex = index
            }
          })
        }
      }
    })
    .catch((err) => {
      console.log('获取圈子列表数据失败', err)
    })
}
const tabbarItemClass = (index?: number) => {
  if (index === state.currentTabbarIndex) {
    return 'tn-classify__tabbar__item--active tn-bg-white'
  } else {
    let clazz = 'tn-gray-light_bg'
    if (
      state.currentTabbarIndex > 0 &&
      index === state.currentTabbarIndex - 1
    ) {
      clazz += ' tn-classify__tabbar__item--active--prev'
    }
    if (
      state.currentTabbarIndex < state.tabbar.length &&
      index === state.currentTabbarIndex + 1
    ) {
      clazz += ' tn-classify__tabbar__item--active--next'
    }
    return clazz
  }
}

// 点击了分类导航
const clickClassifyNav = (index: number) => {
  if (state.currentTabbarIndex === index) {
    return
  }
  state.currentTabbarIndex = index
  handleLeftScrollView(index)
  switchClassifyContent()
}

// 点击分类后，处理scrollView滚动到居中位置
const handleLeftScrollView = (index: number) => {
  const tabbarItemTop =
    state.tabbarItemInfo[index].top - state.scrollViewBasicTop
  if (tabbarItemTop > state.scrollViewHeight / 2) {
    state.leftScrollViewTop =
      tabbarItemTop -
      state.scrollViewHeight / 2 +
      state.tabbarItemInfo[index].height
  } else {
    state.leftScrollViewTop = 0
  }
}
// 切换对应分类的数据
const switchClassifyContent = () => {
  // state.rightScrollViewTop = 1
  // nextTick(() => {
  //   state.rightScrollViewTop = 0
  // })
  state.subClassify[0].name = state.tabbar[state.currentTabbarIndex]
}

// 定义一个异步函数来获取搜索栏的rect信息
const getSearchBarRect = async () => {
  return new Promise((resolve, reject) => {
    const query = uni.createSelectorQuery() // 使用uni.createSelectorQuery()而不是createSelectorQuery().in(this)
    query
      .select('.tn-classify__search--wrap')
      .boundingClientRect((rect) => {
        if (rect) {
          resolve(rect) // rect是一个对象，包含了所选元素的布局信息
        } else {
          reject(new Error('无法获取搜索栏的rect信息'))
        }
      })
      .exec()
  })
}

const getScrollViewInfo = async () => {
  try {
    const rect = await getSearchBarRect()
    const systemInfo = uni.getSystemInfoSync()

    // 计算scrollView的顶部位置（考虑状态栏高度和搜索栏底部位置
    state.scrollViewBasicTop =
      systemInfo.statusBarHeight + rect.bottom + uni.upx2px(10)

    // 计算scrollView的高度（考虑安全区域高度、状态栏高度、搜索栏底部位置和额外间距
    state.scrollViewHeight =
      systemInfo.safeArea.height +
      systemInfo.statusBarHeight -
      rect.bottom -
      uni.upx2px(10) -
      49
  } catch {
    // 如果获取失败，则尝试重新获取（这里使用简单的递归，但最好使用更健壮的重试机制
    setTimeout(() => {
      getScrollViewInfo()
    }, 10)
  }
}

// 获取分类菜单每个item的信息
const getTabbarItemRect = () => {
  const view = uni.createSelectorQuery()
  for (let i = 0; i < state.tabbar.length; i++) {
    view.select(`#tabbar_item_${i}`).boundingClientRect()
  }
  view.exec((res) => {
    if (!res.length) {
      setTimeout(() => {
        getTabbarItemRect()
      }, 10)
      return
    }
    // 将每个分类item的相关信息
    res.map((item: { top: any; height: any }) => {
      return state.tabbarItemInfo.push({
        top: item.top,
        height: item.height,
      })
    })
  })
}

// 跳转到圈子详情页面
const navCirclesDetailPage = (circlesId: number) => {
  tnNavPage(`/circlesPages/detail?circlesId=${circlesId}`)
}

onLoad((options) => {
  getCirclesLists()
  if (options?.circlesTypeName) {
    state.circlesTypeName = options.circlesTypeName
  }
})

onMounted(() => {
  nextTick(() => {
    getScrollViewInfo()
    getTabbarItemRect()
  })
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    >
      <!-- <template #right>
        <view class="right-operation"> 创建圈子 </view>
      </template> -->
      圈子分类
    </TnNavbar>

    <view
      class="tn-classify__wrap tn-bg-white"
      :style="{ paddingTop: `${navbarHeight + 10}px` }"
    >
      <!-- 搜索框 -->
      <view class="tn-classify__search--wrap search-box-container">
        <view class="tn-color-gray--dark search-box-item custom-search-box">
          <TnSearchBox
            v-model="state.searchName"
            :border="false"
            :search-button="false"
            text-align="left"
            placeholder-icon="search-list"
            placeholder="请输入圈子名称"
            @change="changeSearchBox"
          />
        </view>
      </view>

      <!-- 分类列表和内容 -->
      <view class="tn-classify__container">
        <view
          class="tn-classify__container__wrap tn-flex tn-flex-nowrap justify-around"
        >
          <!-- 左边容器 -->
          <scroll-view
            class="tn-classify__left-box left-width"
            :scroll-top="state.leftScrollViewTop"
            scroll-y
            scroll-with-animation
            :style="{ height: state.scrollViewHeight + 'px' }"
          >
            <view
              v-for="(item, index) in state.tabbar"
              :id="`tabbar_item_${index}`"
              :key="index"
              class="tn-classify__tabbar__item tn-flex justify-center items-center"
              :class="[tabbarItemClass(index)]"
              @tap.stop="clickClassifyNav(index)"
            >
              <view class="tn-classify__tabbar__item__title">{{ item }}</view>
            </view>
          </scroll-view>

          <!-- 右边容器 -->
          <scroll-view
            class="tn-classify__right-box"
            scroll-y
            :scroll-top="state.rightScrollViewTop"
            :style="{ height: state.scrollViewHeight + 'px' }"
          >
            <block v-if="state.subClassify && state.subClassify.length > 0">
              <view class="tn-classify__content">
                <!-- 分类内容子栏目 -->
                <view
                  v-for="(item, index) in state.subClassify"
                  v-show="state.currentTabbarIndex == index"
                  :key="index"
                  class="tn-classify__content__sub-classify tn-padding-xs"
                >
                  <view
                    class="tn-classify__content__sub-classify--title tn-text-lg tn-mt-xs"
                    >{{ item.name }}
                  </view>

                  <view
                    v-if="item.circles.length > 0"
                    class="tn-classify__content__sub-classify__content tn-flex tn-flex-wrap items-center justify-start"
                  >
                    <view
                      v-for="(sub_item, sub_index) in item.circles"
                      :key="sub_index"
                      class="tn-flex justify-start items-start tn-p-sm tn-shadow tn-radius tn-mb-sm"
                      style="width: 100%"
                    >
                      <view class="tn-flex items-center">
                        <view
                          class="image-pic"
                          :style="
                            'background-image:url(' +
                            FILE_URL +
                            sub_item.image +
                            ')'
                          "
                        >
                          <view class="image-circles" />
                        </view>
                      </view>
                      <view
                        class="tn-pl-sm"
                        style="width: 40vw; height: 100rpx"
                      >
                        <view class="tn-flex justify-between items-center">
                          <text class="tn-color-black tn-text-ellipsis-1">
                            {{ sub_item.name }}
                          </text>
                        </view>
                        <view
                          class="tn-flex justify-between items-center tn-pt-sm"
                        >
                          <view
                            class="tn-text-ellipsis-1"
                            style="color: #9c9c9c"
                          >
                            <text class="tn-text-sm">
                              {{ sub_item.follow_total }}圈友 ·
                              {{ sub_item.dynamic_total }}动态
                            </text>
                          </view>
                        </view>
                      </view>
                      <view
                        class="tn-flex justify-end items-center"
                        style="width: 15vw; height: 100rpx"
                      >
                        <TnButton
                          text-color="#FFFFFF"
                          font-size="25rpx"
                          :custom-style="{
                            borderRadius: '50rpx',
                            padding: '14rpx 20rpx',
                          }"
                          @click="navCirclesDetailPage(sub_item.id)"
                        >
                          进入
                        </TnButton>
                      </view>
                    </view>
                  </view>
                  <view
                    v-else
                    class="tn-classify__content__sub-classify__content tn-flex tn-flex-wrap items-center justify-center tn-pt-xl"
                  >
                    <TnEmpty mode="data" size="xl" color="#e6e6e6" />
                  </view>
                </view>
              </view>
            </block>
          </scroll-view>
        </view>
      </view>
    </view>
  </PageContainer>
</template>
<style lang="scss" scoped>
@use './styles/classify.scss';
</style>
